var express = require('express');
var router = express.Router();
var AipFaceClient = require("baidu-aip-sdk").face;
var HttpClient = require("baidu-aip-sdk").HttpClient;
HttpClient.setRequestOptions({ timeout: 5000 });
// 设置APPID/AK/SK
const APP_ID = "116039351"
const API_KEY = "MadFM4WnJ5W19GIIKFC9PJMu"
const SECRET_KEY = "dbqFPISpkN75VCKyB2QjEh5ALgwzLN7A"
// 新建一个对象，建议只保存一个对象调用服务接口
var client = new AipFaceClient(APP_ID, API_KEY, SECRET_KEY);
let faceVerificationWithLiveness = async (image) => {
  try {
    const detectResult1 = await client.faceverify([
      {
        image: image,
        image_type: 'BASE64'
      }]).then(function (result) {
        return result
      });
    
    const isLive1 = detectResult1 && detectResult1.result && detectResult1.result.face_list && detectResult1.result.face_list.length > 0 && detectResult1.result.face_liveness > 0.9;
    if (!isLive1) {
      console.log('活体检测失败')
      return 400;
    }
    var imageType = "BASE64";
    var groupIdList = "A1";
    //调用人脸搜索
    const detectResult2 = await client.search(image, imageType, groupIdList).then(function (result) {
      return result
    }).catch(function (err) {
      // 如果发生网络错误
      console.log(err);
    });
    if (detectResult2.error_code === 0 && detectResult2.result.user_list[0].score > 80) {
      console.log('人脸验证成功')
      return 200;
    } else {
      console.log('人脸验证失败')
      return 402;
    }

  } catch (err) {
    console.error("人脸验证或活体检测过程中发生错误:", err);
    return 500;
  }
}

// 人脸验证
router.post('/face-verification', async (req, res) => {
  const { faceData } = req.body;
  await faceVerificationWithLiveness(faceData).then(code => {
    console.log(code)
    if (code === 200) {
      res.send({
        code: 200,
        message: '人脸验证成功'
      })
    } else if (code === 400) {
      res.send({
        code: 400,
        message: '活体检测失败'
      })
    } else if (code === 402) {
      res.send({
        code: 402,
        message: '人脸验证失败'
      })
    }
  })
  })

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
